using UnityEngine;
using System.Collections;

/**
 * Script of High score display (in game).
 * The purpose of this class is to display the best time of the player while playing.
 * @author Benjamin Bruneau
 */
public class DisplayHighScoreScript : MonoBehaviour {
	
	private const int TIMEMAXLENGTH = 11; //Time string maxlength
	
	private const float DEFAULT_TIME = 100000f; // Default time
	
	private const string DISPLAY_PREFIX = "Best : "; // Prefix to display
	private const string DEFAULT_TIME_STRING = "--:--.--"; // Prefix to display
	private const string PREFIX = "LevelScene"; // Level prefix name
	private const string SAVE_MANAGER_NAME = "SaveManager"; // Save Manager GameObject's name
	
	private GameObject _saveManager; // Save manager GameObject
	
	public GameObject _dataContainer; // Data container GameObject
	
	
	
	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start () {
	
		//Initialized because this object moves through scenes
		_saveManager = GameObject.Find (SAVE_MANAGER_NAME);
		this.GetComponent<TextMesh>().text = DISPLAY_PREFIX + convertTime(getHighScore());
	}

	/**
	 * Gets previous high score.
	 * @return float
	 */
	private float getHighScore()
	{
		int levelNumber = int.Parse(_dataContainer.GetComponent<DataContainerScript>()._currentLevel.Replace(PREFIX,""));
		float highScore = float.Parse((((ArrayList)_saveManager.GetComponent<SaveManagerScript>()._sequence[levelNumber-1])[2]).ToString());
		return highScore;
	}
	
	/**
	 * Converts time for display.
	 * @param float
	 * @return string
	 */
	private string convertTime(float pTime)
	{
		string timeString;
		if(pTime != DEFAULT_TIME)
		{
			//Format it
			string tempTimeString = System.TimeSpan.FromSeconds(pTime).ToString();
			
			if (tempTimeString.Length < TIMEMAXLENGTH)
			{
				timeString = tempTimeString.Substring(3);
			} else {
				timeString = tempTimeString.Substring(3,8);
			}
		} else {
			timeString = DEFAULT_TIME_STRING;
		}
		return timeString;
	}
	
}
